<template>
  <div class="module-header">
    {{ `创建库存` }}
    <div class="module-header-search">
      <el-button-group>-
        <el-button size="default" type="primary" @click="backToOutList">返回</el-button>
        <el-button size="default" type="primary" @click="confirmInputStoreOut()">提交</el-button>
      </el-button-group>
    </div>
  </div>
  <div class="create-order-view">
    <div class="input-order-view">
      <el-row>
        <el-col :span="14">
          <el-form :model="outCreateData" label-width="100px" size="default">
            <el-form-item label="发货单位：">
              <el-input readonly disabled v-model="sender"/>
            </el-form-item>
            <el-form-item label="出库单号：">
              <el-input v-model="outCreateData.outCode"/>
            </el-form-item>
            <el-form-item label="入库日期：">
              <el-date-picker value-format="YYYY-MM-DD" type="date" placeholder="选择出库日期" size="default"
                              v-model="outCreateData.outDate" style="width: 100%"/>
            </el-form-item>
            <el-form-item label="订货客户：">
              <el-select v-model="outCreateData.orderCustomer" clearable filterable placeholder="选择订货客户"
                         @change="onOrderCustomerSelect" style="width: 100%">
                <el-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="收货客户：">
              <el-select v-model="outCreateData.deliveryCustomer" clearable filterable placeholder="选择收货客户"
                         @change="onCustomerSelect" style="width: 100%">
                <el-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-form>
          <div style="padding-top: 20px">
            <el-table max-height="430" :data="outDetailEntities" style="width: 100%" empty-text="">
              <el-table-column prop="bomCode" label="物料编号" width="100" fixed="left"></el-table-column>
              <el-table-column prop="bomName" label="物料名称"></el-table-column>
              <el-table-column prop="price" label="单价" width="80"></el-table-column>
              <el-table-column prop="quantity" label="订单数量" width="80"></el-table-column>
              <el-table-column prop="note" label="备注" width="100px"></el-table-column>
              <el-table-column label="管理" fixed="right" width="130">
                <template #default="scope">
                  <div style="display:flex; justify-content: space-between">
                    <el-button size="small" @click="handleDetailEdit(scope.$index, scope.row)">修改</el-button>
                    <el-button size="small" type="danger" @click="handleDetailDelete(scope.$index)">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div>
              <div class="add-bom-container" @click="addOutBom">
                <div class="">
                  <CirclePlusFilled/>
                </div>
                添加物料
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
  <el-dialog class="add-bom-dialog" v-model="selectBomVisible" title="添加出库物料品类" width="650px" draggable>
    <el-row>
      <el-col :span="23">
        <el-form :model="outEntityData" label-width="100px" size="default">
          <el-form-item label="选择物料：">
            <el-select v-model="outEntityData.bomId" clearable filterable placeholder="选择物料"
                       @change="onBomSelect($event)"
                       style="width:100%;">
              <el-option v-for="item in bomList" :key="item.id" :label="item.code + ' <=> ' + item.name"
                         :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="出库数量：">
            <el-input v-model="outEntityData.quantity"/>
          </el-form-item>
          <el-form-item label="备注信息：">
            <el-input v-model="outEntityData.note"/>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="default" @click="closeBomSelectDialog">取消</el-button>
        <el-button size="default" type="primary" @click="confirmBomSelect">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import {mixins, Options} from 'vue-class-component';
import {CirclePlusFilled, Edit, ArrowDown} from "@element-plus/icons-vue";
import TencentOcrResultModel, {TableDetection} from "@/models/TencentOcrResultModel";
import DictMixin from "@/mixins/dict.mixin";
import BomModel from "@/models/BomModel";
import StoreOutModel from "@/models/StoreOutModel";
import CustomerModel from "@/models/CustomerModel";
import {selectOut, ocrStoreOut, selectOutCode, saveStoreOut} from '@/apis/out.api';
import {BomEntityItem} from "@/models/common.model";
import {StoreOutDetailRequestModel, StoreOutRequestModel} from "@/models/StoreOutRequestModel";
import {ElMessageBox, ElMessage} from "element-plus";
import DictionaryModel from "@/models/DictionaryModel";

@Options({
  components: {CirclePlusFilled, Edit, ArrowDown}
})
export default class StoreCreateView extends mixins(DictMixin) {
  // 发货单位
  private sender = '北京圣美印刷有限责任公司';

  private outDetailEntities: BomEntityItem[] = [];

  // 创建明细表临时数据结构
  private outEntityData: BomEntityItem = new BomEntityItem();
  // 出库单对象
  private outCreateData: StoreOutModel = new StoreOutModel();

  // 编辑行的临时保存值
  private editRowIndex = -1;

  private customerList: CustomerModel[] | null = null;
  private bomList: BomModel[] | null = null;
  private selectBomVisible = false;

  private isDragOver = false

  async created() {
    // 加载字典
    this.customerList = this.getUserDict<CustomerModel>('CUSTOMER_LIST');
    this.bomList = this.getUserDict<BomModel>('BOM_LIST');

    const outCode = (await selectOutCode()).data;
    this.outCreateData = new StoreOutModel(outCode);
  }

  backToOutList() {
    this.$router.push('/out/')
  }

  onOrderCustomerSelect(index: number) {
    if (this.customerList && this.outCreateData) {
      const customer: CustomerModel | null = this.customerList[index - 1]
      this.outCreateData.orderCustomerName = customer?.name ?? '';
    }
  }

  // 选择要送货的客户
  onCustomerSelect(index: number) {
    if (this.customerList && this.outCreateData) {
      const customer: CustomerModel | null = this.customerList[index - 1]
      this.outCreateData.deliveryCustomerName = customer?.name ?? '';
    }
  }

  // 确认添加手动创建的出库单
  confirmInputStoreOut() {
    const model: StoreOutRequestModel = new StoreOutRequestModel();
    model.outCode = this.outCreateData.outCode;
    model.outDate = this.outCreateData.outDate;
    model.orderCustomer = this.outCreateData.orderCustomer;
    model.orderCustomerName = this.outCreateData.orderCustomerName;
    model.deliveryCustomer = this.outCreateData.deliveryCustomer;
    model.deliveryCustomerName = this.outCreateData.deliveryCustomerName;
    model.detailEntities = this.outDetailEntities.reduce((previousValue: StoreOutDetailRequestModel[], currentValue: BomEntityItem): StoreOutDetailRequestModel[] => {
      const item: StoreOutDetailRequestModel = new StoreOutDetailRequestModel();
      item.bom = currentValue.bomId;
      item.price = currentValue.price;
      item.quantity = currentValue.quantity;
      item.note = currentValue.note;
      item.outCode = this.outCreateData.outCode;
      item.outDate = this.outCreateData.outDate;
      item.status = 0;
      previousValue.push(item);
      return previousValue;
    }, []);
    debugger
    if (model.orderCustomer && model.outDate && model.outCode && model.detailEntities && model.detailEntities.length > 0) {
      saveStoreOut(model).then((value: StoreOutModel) => {
        if (value.id) {
          ElMessageBox.confirm('出库单创建成功，点击确定继续创建出库单，点击取消关闭', '提示信息', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info',
          }).then(() => {
            this.outEntityData = new BomEntityItem();
            this.editRowIndex = -1;
            this.selectBomVisible = false;
            this.outCreateData = new StoreOutModel();
            this.outDetailEntities.length = 0;
          }).catch(() => {
            this.outEntityData = new BomEntityItem();
            this.editRowIndex = -1;
            this.selectBomVisible = false;
          })
        }
      });
    } else {
      ElMessage.info({
        type: 'error',
        message: '信息填写不完整',
      })
    }
  }

  // 订单明细编辑
  handleDetailEdit(index: number, row: BomEntityItem): void {
    this.outEntityData = row;
    this.editRowIndex = index;
    this.selectBomVisible = true;
  }

  // 订单明细删除
  handleDetailDelete(index: number): void {
    this.outDetailEntities.splice(index, 1);
  }

  // 确认物料选择
  confirmBomSelect() {
    this.selectBomVisible = false;
    if (this.outEntityData.bomId) {
      const detailEntity: BomEntityItem = new BomEntityItem()

      detailEntity.bomId = this.outEntityData.bomId;
      detailEntity.bomCode = this.outEntityData.bomCode + '';
      detailEntity.bomName = this.outEntityData.bomName + '';
      detailEntity.price = this.outEntityData.price;
      detailEntity.quantity = this.outEntityData.quantity;
      detailEntity.note = this.outEntityData.note ?? '';

      this.outDetailEntities.splice(this.editRowIndex > -1 ? this.editRowIndex : this.outDetailEntities.length - 1, this.editRowIndex > -1 ? 1 : 0, detailEntity);
      this.outEntityData = new BomEntityItem();
    }
  }

  closeBomSelectDialog() {
    this.selectBomVisible = false;
    this.outEntityData = new BomEntityItem()
  }

  onBomSelect(index: number) {
    if (this.bomList) {
      const bom: BomModel | null = this.bomList[index - 1]
      this.outEntityData.bomId = bom.id;
      this.outEntityData.bomCode = bom.code;
      this.outEntityData.bomName = bom.name;
      this.outEntityData.price = bom.price;
    }
  }

  onFastFill(cmd: string) {
    switch (cmd) {
      case 'empty': // 空
        this.outEntityData.note = '';
        break;
      case 'tjmy': // 天津明英加放3%
      {
        this.outEntityData.quantity = Math.floor(this.outEntityData.quantity / 1.03);
        this.outEntityData.note = '加放' + Math.ceil(this.outEntityData.quantity * 0.03);
      }
        break;
      case 'sdhlh': // 山东汇利华加放千分之五
      {
        this.outEntityData.quantity = Math.floor(this.outEntityData.quantity / 1.005);
        this.outEntityData.note = '加放' + Math.ceil(this.outEntityData.quantity * 0.005);
      }
        break;
      case 'bws1218': // 统一系 合成纸不干胶
        this.outEntityData.note = '合成纸不干胶';
        break;
      case 'aws1315': // 统一系 普通纸不干胶
        this.outEntityData.note = '普通纸不干胶';
        break;
      default:
    }
  }

  addOutBom() {
    this.outEntityData = new BomEntityItem()
    this.selectBomVisible = true;
  }

  beforeUnmount(): void {
    this.outCreateData = new StoreOutModel();
  }

  // 拖拽识别出库单截图与pdf
  onHolderDragOver(e: DragEvent): void {
    e.preventDefault();
    this.isDragOver = true;
  }

  onHolderDragLeave(): void {
    this.isDragOver = false;
  }

  onHolderDragDrop(e: DragEvent): void {
    e.preventDefault();
    this.isDragOver = false;
    if (e.dataTransfer && e.dataTransfer.files.length > 0) {
      // 在此处处理上传文件的逻辑
      ocrStoreOut(e.dataTransfer.files[0]).then((value: TencentOcrResultModel) => {
        if (value.TableDetections.length === 1) {
          console.log()
        } else if (value.TableDetections.length === 2) {
          // 统一订单
          this.resolveTYOrderData(value.TableDetections)
        }
      })
    }
  }

  resolveTYOrderData(tableDetections: TableDetection[]): void {
    console.log(tableDetections)
  }

  resolveLROrderData(tableDetections: TableDetection[]): void {
    console.log(tableDetections)
  }
}

</script>

<style scoped lang="scss">
.create-order-view {
  width: 100%;
  height: calc(100% - 50px);
  position: relative;

  .order-drag-view {
    display: none;
  }

  &.show-drag-over-state {
    .order-drag-view {
      pointer-events: none;
      position: absolute;
      z-index: 1000;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.2);
      padding: 20px;
      display: block;

      .order-drag-border {
        border: dashed #eee 10px;
        height: 100%;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        span {
          font-size: 48px;
          color: #ddd;
        }
      }
    }
  }

  .input-order-view {
    padding: 40px;
  }
}

.add-bom-container {

  height: 60px;
  padding-top: 15px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  line-height: 20px;
  cursor: pointer;

  & > div {
    height: 30px;
    width: 30px;
  }
}

.add-bom-dialog {
  .el-dialog__footer {
    text-align: center;
  }
}
</style>